<template>
  <div class="login">
    <div class="header">
      <div class="logo"><img src="@/assets/logo.png" alt="" /></div>
    </div>
    <div class="main">
      <form class="login-form" @submit.prevent="submit">
        <div class="error">{{ error }}</div>
        <div class="item">
          <div class="tit">账号</div>
          <div class="con">
            <input ref="inputName" v-model.trim="form.username" type="text" />
          </div>
        </div>
        <div class="item">
          <div class="tit">密码</div>
          <div class="con">
            <input ref="inputPwd" v-model.trim="form.password" type="text" />
          </div>
        </div>
        <div class="item">
          <input id="keepLogin" v-model="form.keep" type="checkbox" />
          <label for="keepLogin">记住当前账号</label>
        </div>
        <button class="btn-login">登录</button>
      </form>
    </div>
    <footer class="footer">
      &copy;福州八六三软件专业孵化器服务中心<br />联系电话：0591-87860300
    </footer>
  </div>
</template>

<script>
import { inject, reactive, ref } from "@vue/composition-api";
import { Dialog, Toast } from "vant";

export default {
  name: "Login",
  setup(props, { root: { $router } }) {
    /**
     * @type {AppStore}
     */
    const app = inject("app");

    const error = ref("");
    const inputName = ref();
    const inputPwd = ref();

    const form = reactive({
      username: "phone",
      password: "123456",
      keep: false
    });

    function validate() {
      if (!form.username) {
        error.value = "请输入账号";
        inputName.value.focus();
      } else if (!form.password) {
        error.value = "请输入密码";
        inputPwd.value.focus();
      } else {
        error.value = "";
        return true;
      }
    }

    async function submit() {
      if (!validate()) {
        return;
      }

      try {
        Toast.loading();
        await app.login(form, form.keep);
        $router.push("/");
      } catch (e) {
        console.error(e);

        const { error_description } = e;

        if (error_description) {
          error.value = error_description;
          return;
        }

        if (!e._handler) {
          Dialog.alert({ message: e.message });
        }
      } finally {
        Toast.clear();
      }
    }

    return {
      error,
      inputName,
      inputPwd,
      form,
      submit
    };
  }
};
</script>
